package com.wafersystems.cloud.web.websocket;

import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

@Service
public class WebSocketInterceptor implements HandshakeInterceptor {

  @Override
  public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
      WebSocketHandler handler, Exception exception) {}

  @Override
  public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
      WebSocketHandler handler, Map<String, Object> map) throws Exception {
    if (request != null) {
      HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
      HttpSession session = servletRequest.getSession();
      if (session != null) {
        map.put("uniqueId", ((ServletRequest) servletRequest).getParameter("uniqueId"));
        return true;
      }
    }
    return false;
  }

}
